package com.weibo.click;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.KeyStroke;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj.barcode.ConstantStri;

/* 1.本class的作用是接受2个参数： 发送String和X，Y坐标
 * 2. 然后把字符串首先存储到Clipboard，再在对应的坐标上点击mouse，然后CTR+V 粘贴数据
 * 3、本class的server方法将保持一个监听器
 * */
public class ClipboardUtils {
	Robot robot=null;
	Log logger = LogFactory.getLog(localHttpLisener.class);
	/* 复制字符串 */
	private String copy(String str) throws UnsupportedFlavorException,
			IOException {
		StringSelection stsel = new StringSelection(str);
		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		clip.setContents(stsel, stsel);
		Transferable clipT = clip.getContents(null);
		if (clipT != null) {
			// 检查内容是否是文本类型
			if (clipT.isDataFlavorSupported(DataFlavor.stringFlavor))
				return (String) clipT.getTransferData(DataFlavor.stringFlavor);
		}
		return null;
	}
	private void pasteContents(Robot robot) {
	    robot.delay(8);
		robot.keyPress(KeyEvent.VK_CONTROL);
	    robot.delay(2);
		robot.keyPress(KeyEvent.VK_CONTROL);
	    robot.delay(6);
		robot.keyPress(KeyEvent.VK_CONTROL);
	    robot.delay(1);
		robot.keyPress(KeyEvent.VK_CONTROL);
	    robot.delay(3);
		robot.keyPress(KeyEvent.VK_CONTROL);
	    robot.delay(57);
		robot.keyPress(KeyEvent.VK_V);
	    robot.delay(1);
		robot.keyPress(KeyEvent.VK_V);
	    robot.delay(4);
		robot.keyPress(KeyEvent.VK_V);
	    robot.delay(5);
		robot.keyPress(KeyEvent.VK_V);
	    robot.delay(3);
		robot.keyPress(KeyEvent.VK_V);
	    robot.delay(54);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(9);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(1);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(4);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(5);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(3);
		robot.keyRelease(KeyEvent.VK_V);
	    robot.delay(32);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	    robot.delay(2);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	    robot.delay(6);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	    robot.delay(1);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	    robot.delay(3);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	    robot.delay(6);
		robot.keyRelease(KeyEvent.VK_CONTROL);
	}

	public ClipboardUtils() {
		try {
			this.robot = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}
	protected  void type(String s)
	  {
	    byte[] bytes;
		try {
			bytes = s.getBytes("UTF-8");
		    for (byte b : bytes){
		        int code = b;
		        //System.out.print(" Key Code="+code+";");
		        // keycode only handles [A-Z] (which is ASCII decimal [65-90])
		        if (code > 96 && code < 123){
		    	  code = code - 32;
		        }
			    robot.delay(5);
			    robot.keyPress(code);
			    robot.delay(4);
			    robot.keyRelease(code);
		    }//FOR
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	  }

	/* 鼠标移动，并且20毫秒以后点击对应的坐标 */
	protected void mouseMoveAndClick(int x, int y) {
		robot.mouseMove(x, y);
		robot.delay(945);
		robot.mousePress(KeyEvent.BUTTON1_MASK);
		robot.delay(22);
		robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
	}
	private void mouseMoveAndDoubleClick(int x, int y) {
		robot.mouseMove(x, y);
		robot.delay(845);
		robot.mousePress(KeyEvent.BUTTON1_MASK);
		robot.delay(9);
		robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
		robot.delay(11);
		robot.mousePress(KeyEvent.BUTTON1_MASK);
		robot.delay(9);
		robot.mouseRelease(KeyEvent.BUTTON1_MASK);// 松开鼠标左键
	}
	
    public void clickFireFoxOld(int xPosText,int yPosText,int xPosSend,int yPosSend,String message){
		try {
			mouseMoveAndClick(xPosText, yPosText);
			robot.delay(40);
			String uniWord=null;
			String msg=new String(message.trim());
			for(int idx=0;idx<msg.length();idx++){
				char [] str={msg.charAt(idx)};
				String code=new String(str);
				//自己定义的换行符号！
				if(code.equals("|")){
				    robot.keyPress(KeyEvent.VK_ENTER);
				    robot.delay(64);
				    robot.keyRelease(KeyEvent.VK_ENTER);
					robot.delay(111);
					continue;
				}
				uniWord=chinaToUnicode(code);
				logger.info("uniWord is :"+code+"---"+uniWord);
				pressUnicode(uniWord);
			}
		    robot.keyPress(KeyEvent.VK_ENTER);
		    robot.delay(4);
		    robot.keyRelease(KeyEvent.VK_ENTER);
			robot.delay(111);
			mouseMoveAndClick(xPosSend, yPosSend);//虚拟点击发送按鈕
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    /*需要模拟用户不停移动鼠标的行为？？*/
    public void clickFireFox(String message){
		try {
			String uniWord=null;
			String msg=new String(message.trim());
			copy(new String(msg.getBytes("UTF-8")));
			//Ctrl+F2启动GhostMouse软件录制的脚本，完全真实的模拟鼠标移动！
			robot.delay(40);
		    robot.keyPress(KeyEvent.VK_CONTROL);
			robot.delay(8);
		    robot.keyPress(KeyEvent.VK_F2);
			robot.delay(12);
		    robot.keyRelease(KeyEvent.VK_F2);
			robot.delay(9);
		    robot.keyRelease(KeyEvent.VK_CONTROL);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    /*采用鼠标和键盘模拟FF关闭和打开！*/
    public void clickFireFoxLogout(){
		try {
			//CTRL+SHIFT+DEL clean FF的缓存
			mouseMoveAndClick(1126,15);//把焦点转移到Firefox上！
			robot.delay(1129);
	 		//CTRL+SHIFT+DEL clean FF的缓存
			robot.keyPress(KeyEvent.VK_CONTROL);
		    robot.delay(57);
			robot.keyPress(KeyEvent.VK_SHIFT);
		    robot.delay(511);
			robot.keyPress(KeyEvent.VK_DELETE);
		    robot.delay(245);
			robot.keyRelease(KeyEvent.VK_DELETE);
		    robot.delay(57);
			robot.keyRelease(KeyEvent.VK_SHIFT);
		    robot.delay(111);
			robot.keyRelease(KeyEvent.VK_CONTROL);
		    robot.delay(2111);
			robot.keyPress(KeyEvent.VK_ENTER);
		    robot.delay(3545);
			robot.keyRelease(KeyEvent.VK_ENTER);
			logger.info("clickFireFoxLogout: FF history cleaned!");
		    robot.delay(5111);
			Runtime.getRuntime().exec(ConstantStri.FFLogout);
		}catch (Exception e) {
			logger.info("Exception in clickFireFoxLogout!");
		}finally{
		}
    }
    /*采用鼠标和键盘模拟FF关闭和打开！*/
    public void clickFireFoxLogin(String user,String pass,String verify){
		try {
			logger.info("clickFireFoxLogin: user="+user+" pass="+pass+" verify="+verify);
			mouseMoveAndDoubleClick(800,286);//input user
			robot.delay(250);
			type(user);
			mouseMoveAndDoubleClick(800,347);// input pass
			robot.delay(250);
			type(pass);
			robot.delay(335);
			if(verify.trim().equals("yes")){
				logger.info("clickFireFoxLogin: mouseMoveAndClick(840,530)"+verify);
				mouseMoveAndClick(840,530);//出现验证码
				robot.delay(859);
				mouseMoveAndClick(840,408);
			}else if(verify.trim().equals("no")){
				logger.info("clickFireFoxLogin: mouseMoveAndClick(840,408)"+verify);
				mouseMoveAndClick(840,408);//没有验证码
				robot.delay(61);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
    }
    /**
	 * 把中文转成unicode码的字符数组 - 24744
	 * @param chiWord -  中文或者英文字符，统一转换为unicode码，通过unicode输入法输入
	 * @return
	 */
	private String chinaToUnicode(String chiWord){
		String result="";
		for (int i = 0; i < chiWord.length(); i++){
            int chr1 = (char) chiWord.charAt(i);
            if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)
                result+=Integer.toHexString(chr1);
            //中文标点的UNICODE--> http://ms.n.blog.163.com/blog/static/18595352009112373955832/    
            }else if(  
            	chr1==183 
             || chr1==215 
             || chr1==8212 
             || chr1==8216 
             || chr1==8217 
             || chr1==8220 
             || chr1==8221 
             || chr1==8230 
             || chr1==12289 
             || chr1==12290 
             || chr1==12298 
             || chr1==12299 
             || chr1==12302 
             || chr1==12303 
             || chr1==12304 
             || chr1==12305 
             || chr1==65281 
             || chr1==65288 
             || chr1==65289 
             || chr1==65292 
             || chr1==65306 
             || chr1==65307 
             || chr1==65311)
           {
                result+=Integer.toHexString(chr1);
            }
            else{
            	result+="00"+Integer.toHexString(chr1);
            }
        }
		 //logger.info("chinaToUnicode:="+result);
		return result;
	}

	/**
	 * 判断是否为中文字符
	 * @param c
	 * @return
	 */
	
	public  boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
	/**
	 * 采用微软的unicode输入法，输入中文
	 * @param unicode
	 */
	public  void pressUnicode(String unicode){
	    robot.keyPress(KeyEvent.VK_BACK_QUOTE);
	    robot.delay(17);
	    robot.keyRelease(KeyEvent.VK_BACK_QUOTE);
	    robot.delay(11);
	    robot.keyPress(KeyEvent.VK_U);
	    robot.delay(18);
	    robot.keyRelease(KeyEvent.VK_U);
	    type(unicode);
	}	
	
	
	public static void main(String[] args) {
		try {
			ClipboardUtils clip = new ClipboardUtils();
			String msg=new String("a学习/调皮要加，骄傲/惊讶要减，" +
					"机会/玫瑰要乘，懒惰/玫瑰要除。免fèi " +
					"分享 :翻qiáng软件，电子书 http://t.cn/zWjzUER    ");
			//clip.clickFireFox(msg);
			clip.clickFireFoxLogout();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
